<template>
  <div
    class="video-box"
    :style="{background: showDialog === 'showClassPic' ?
      `url(${classInfo.ClassImg}) 50% 50%/cover no-repeat` : ''}"
  >
    <VTcPlayer
      v-if="options.m3u8 && isPlayerVisible"
      ref="vTcPlayer"
      :options="options"
      class="player-wrapper"
      @load="onLoad"
      @play="onPlay"
      @pause="onPause"
      @timeupdate="onTimeupdate"
      @error="onError"
      @resize="onResize"
    />
    <videoDialog
      v-if="showDialog && showDialog !== 'showClassPic'"
      :show-dialog="showDialog"
      @selectAction="onClickBtn"
    />
    <img
      id="play-round"
      src="~assets/class/play_round.png"
      class="play-round"
      style="display: none;"
    >
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapState } from 'vuex'
import { loadScript, browser as browserInfo, isiOS, rem2px } from '@/lib/utils'
import { VTcPlayer, TcPlayer, TcPlayerOptions } from 'v-tcplayer'
import { UAParser } from 'ua-parser-js'
const parser = new UAParser()
const parsedUA = parser.getResult()
const deviceInfo = `H5@|@|${parsedUA.browser.name}@|${parsedUA.browser.version}`
export default Vue.extend({
  components: {
    videoDialog: () => import('components/Video/VideoDialog.vue'),
    VTcPlayer,
  },
  // eslint-disable-next-line vue/require-default-prop
  // eslint-disable-next-line vue/require-prop-types
  props: ['sectionInfo', 'isFreeCourse', 'lengthInfo'],
  data () {
    const coverImg = this.sectionInfo.CourseImg
    return {
      packageId: this.$route.query.packageId || '',
      keyId: '',
      videoInfo: {} as VideoInfo,
      watchedTime: 0,
      fromLastSubmitTime: 0,
      isPlayerVisible: true, // 视频是否可见
      player: null as any as TcPlayer,
      isPlaying: false,
      doNotHeatBeat: false,
      showDialog: '', // 窗口提示
      planInterval: 0,
      finishedPlay: false,
      options: {
        width: Math.floor(rem2px(9.36)),
        height: Math.floor(rem2px(5.24)),
        // width: 'auto' as any,
        // height: 'auto' as any,
        m3u8: '',
        autoplay: false, // 只对大部分PC平台生效
        x5_player: true,
        // x5_type: 'h5',
        poster: { 'style': 'cover', 'src': coverImg || require('assets/default.jpg') },
        hlsUrl: '//lib.baomitu.com/hls.js/0.8.9/hls.min.js',
      } as TcPlayerOptions,
    }
  },
  computed: {
    ...mapState(['userInfo']) as MappedState,
    // 是否试听
    isAudition (): boolean {
      return false
    },

    // 是否试听结束
    isAuditionEnd (): boolean {
      return false
    },
  },
  watch: {
    sectionInfo: {
      handler (newVal, oldVal) {
        if (!newVal.SectionId) {
          return
        }
        // tcplayer切换视频不暂停，手动发起暂停心跳
        console.log('手动发起暂停心跳', this.isPlaying)
        if (this.isPlaying) {
          this.isPlaying = false
          this.clearTimer()
          this.postHeartBeat(1, oldVal)
          this.keyId = ''
        }
        console.log('nnnnn', newVal)
        this.getVideoInfo()
      },
      deep: true,
    },
    showDialog (showFlag) {
      if (showFlag) {
        this.destroyPlayer()
      } else {
        this.isPlayerVisible = true
      }
    },
  },
  beforeDestroy () {
    if (this.player) {
      this.clearTimer()
      this.destroyPlayer()
    }
  },
  created () {
    if (this.sectionInfo.SectionId) {
      this.getVideoInfo()
    }
  },
  methods: {
    // 获取视频详情
    getVideoInfo () {
      console.log('this.sectionInfo', this.sectionInfo)
      const { courseId, SectionId } = this.sectionInfo as VSectionItem
      if (!SectionId || !courseId) {
        return
      }
      if (this.isFreeCourse) {
        this.videoInfo = {
          ...this.sectionInfo,
          SectionName: this.sectionInfo.Name,
        }
        this.watchedTime = this.sectionInfo.LastStudyTime
        this.setPlayerInfo()
        console.log('tcplayer切换视频不', this.isPlaying)
        // tcplayer切换视频不暂停，手动发起开始心跳
        if (this.isPlaying) {
          this.postHeartBeat(0)
        }
      }
    },

    // 创建播放器
    setPlayerInfo () {
      this.isPlayerVisible = true
      this.$set(this.$data.options, 'm3u8', (this.videoInfo as any).PlayUrl)
      if (this.player) {
        this.player.load((this.videoInfo as any).PlayUrl)
        this.player.currentTime(this.watchedTime)
      }
      // 在播放器中设置封面与暂停按钮
      setTimeout(() => {
        const cloneRound = document.getElementById('cloneRound') as HTMLDivElement
        if (cloneRound) {
          return
        }
        let vcpPoster = document.getElementsByClassName('vcp-poster')[0]
        let playRound = document.getElementById('play-round') as HTMLDivElement
        const playRoundClone = playRound.cloneNode(true) as HTMLDivElement
        playRoundClone.id = 'cloneRound'
        playRoundClone.style.display = 'block'
        if (vcpPoster && this.isPlayerVisible) {
          console.log('333333')
          vcpPoster.appendChild(playRoundClone)
        }
      }, 100)
      if (this.finishedPlay) {
        this.playerPlay()
        this.finishedPlay = false
      }
    },

    destroyPlayer () {
      if (this.player) {
        if (this.isPlaying) {
          this.isPlaying = false
          this.postHeartBeat(1)
        }
        this.clearTimer()
        this.player.fullscreen(false)
        this.player.destroy()
        this.player = null as any
        this.isPlayerVisible = false
      }
    },

    playerPause () {
      if (this.player) {
        this.player.fullscreen(false)
        this.player.pause()
      }
    },
    playerPlay () {
      this.player && this.player.play()
    },

    // 开始播放
    onPlay () {
      console.log('开始播放')
      this.showDialog = ''
      this.isPlaying = true
      this.initInterval();
      (document.getElementsByClassName('vcp-loading')[0] as HTMLElement)
        .style.opacity = '0'
    },

    // 视频暂停
    onPause () {
      console.log('视频暂停')
      this.isPlaying = false
      if (this.videoInfo.Duration - this.player.currentTime() > 0.3) {
        this.postHeartBeat(1)
      } else {
        if (this.videoInfo.IsStudy && !this.videoInfo.IsCanNext && this.videoInfo.PaperId !== '') {
          this.showDialog = 'goPaper'
        } else {
          this.onEnded()
        }
      }
      this.clearTimer()
      this.keyId = ''
      if (this.doNotHeatBeat) {
        this.doNotHeatBeat = false
      }
    },

    // 视频加载时
    onLoad () {
      (document.getElementsByClassName('vcp-loading')[0] as HTMLElement)
        .style.opacity = '1'
      this.player = (this.$refs.vTcPlayer as any).vTcPlayer
      this.player.currentTime(this.watchedTime)
    },

    // 视频错误
    onError () {
      this.showDialog = 'showTryAgain'
    },

    onResize () {
      // alert('oooo')
    },

    // 视频结束
    onEnded () {
      this.postHeartBeat(2)
      this.finishedPlay = true
      if ((this.sectionInfo as VSectionItem).index < this.lengthInfo.canPlayLength - 1) {
        console.log('llllla playNext')
        this.$emit('playNext')
      } else {
        this.showDialog = 'showPlayAgain'
      }
      // 避免安卓机在微信端播放完视频后有广告
      if (browserInfo.isQQMBrowser || !isiOS) {
        this.$nextTick(() => {
          this.doNotHeatBeat = true
        })
        this.playerPlay()
        setTimeout(() => {
          this.playerPause()
        }, 0)
      }
    },

    // onTimeUpdate
    onTimeupdate () {
      // this.watchedTime = this.player.currentTime()
      console.log(this.player.currentTime())
      if (this.watchedTime < this.player.currentTime() - 10 && !this.videoInfo.IsCanNext) {
        this.player.currentTime(this.watchedTime)
      } else {
        this.watchedTime = this.player.currentTime()
      }
      if ((this as any).userInfo.UserId === '-1') {
        this.showDialog = 'showLogin'
      }
    },

    // 初始化定时器
    initInterval () {
      console.log('初始化定时器')
      if (this.planInterval === 0) {
        // 微信内加载完视频自动执行一遍开始、暂停
        setTimeout(() => {
          if (this.isPlaying) {
            this.postHeartBeat(0)
          }
        }, 0)
      }
      this.clearTimer()
      this.planInterval = window.setInterval(() => {
        this.postHeartBeat(0)
      }, 1000 * 20)
    },

    clearTimer () {
      if (this.planInterval) {
        window.clearInterval(this.planInterval)
        this.planInterval = 0
      }
    },

    // 被挤掉登录
    netWorkError (res: any) {
      if (res.code === 401) {
        this.keyId = ''
        this.showDialog = 'showLogin'
      } else {
        res.message && this.$toast(res.message)
      }
    },

    // 失败后尝试重新播放
    tryAgain () {
      if (this.player) {
        this.getVideoInfo()
        this.showDialog = ''
      }
    },

    // 重新登录弹窗按钮
    showLoginElement () {
      sessionStorage.setItem('loginFromPage', JSON.stringify({
        from: this.$route.name,
        query: this.$route.query,
      }))
      this.$router.push({ name: 'login' })
    },

    // 去注册按钮
    showRegisterElement () {
      sessionStorage.setItem('loginFromPage', JSON.stringify({
        from: this.$route.name,
        query: this.$route.query,
      }))
      this.$router.push({ name: 'register' })
    },

    // 播完全部点重新播放
    playerAgain () {
      if ((this.sectionInfo as VSectionItem).index < this.lengthInfo.canPlayLength - 1) {
        this.$emit('playNext')
      } else {
        this.playerPlay()
      }
      this.showDialog = ''
    },

    // 弹窗按钮
    onClickBtn () {
      // 登录弹窗按钮
      if (this.showDialog === 'showLogin') {
        this.showLoginElement()
        return
      }
      // 视频获取失败弹窗按钮
      if (this.showDialog === 'showTryAgain') {
        this.tryAgain()
        return
      }
      // 重新播放弹窗按钮
      if (this.showDialog === 'showPlayAgain') {
        this.playerAgain()
        return
      }

      // 免费课详情试听结束后弹窗按钮/试听结束弹窗按钮
      if (this.showDialog === 'goRegister') {
        this.showRegisterElement()
        return
      }

      if (this.showDialog === 'goPaper') {
        this.toPaperDetails()
      }
    },

    toPaperDetails () {
      sessionStorage.setItem('paperFromPage', JSON.stringify({
        from: this.$route.name,
        query: this.$route.query,
      }))
      console.log('routequery', this.$route.query)
      this.$router.push({
        name: 'examTest',
        query: {
          Type: '1',
          PaperId: this.videoInfo.PaperId,
          subj: this.videoInfo.Name,
        },
      })
    },

    // submitType 0：正常播放， 1：播放暂停， 2：播放结束
    postHeartBeat (submitType: number, sectionInfo?: VSectionItem) {
      if (this.doNotHeatBeat) {
        return
      }
      if (submitType === 0 && !this.isPlaying) {
        return
      }
      const RecordTime = ~~this.watchedTime
      if (submitType === 1 &&
        (RecordTime === 0 || +this.videoInfo.LastStudyTime === RecordTime)) {
        return
      }
      const { courseId, SectionId } = sectionInfo || this.sectionInfo as VSectionItem
      this.$axios({
        url: 'ytjysite/ECourse/SubmitVideoLog',
        data: {
          PackageId: this.packageId,
          CourseId: courseId,
          ChapterId: this.videoInfo.ChapterId,
          VideoId: SectionId,
          StudyLogId: this.keyId,
          StudyTime: RecordTime,
          IsFinish: false,
          SourceType: 4,
          ViewWay: 2,
          DeviceInfo: deviceInfo,
          SubmitType: submitType,
          isPlaying: this.isPlaying,
        },
      }, 2).then(res => {
        this.keyId = res.StudyLogId
      }).catch(res => {
        this.netWorkError(res)
      })
    },
  },
})
interface MappedState {
  userInfo: () => UserInfoState
  [k: string]: any
}
interface VideoInfo {
  ChapterId: string
  Name: string
  Description: string
  DownloadUrl: string
  Duration: number
  LastStudyTime: number
  Id: string
  PlayUrl: string
  IsCanNext: boolean
  IsFinish: boolean
  IsStudy: boolean
  PassGrade: number
  Status: number
  StatusStr: string
  PaperId: string
  ClassId: number
  ClassName: string
  CourseName: string
  SectionName: string
}
</script>
<style lang="scss" scoped>
.player-wrapper {
  width: 9.36rem;
  height: 5.24rem;
}
.video-box {
  position: relative;
  height: 100%;
  padding: 0 24px;
  overflow: hidden;
  /deep/ {
    .vcp-error-tips {
      opacity: 0;
    }
    .vcp-loading {
      opacity: 0 !important;
    }
    .vcp-slider {
      background: #f6f6f6;
    }
    .vcp-slider-track,.vcp-slider-thumb {
      background-color: #03C9BB;
    }
    .vcp-playtoggle {
      background: url('~assets/class/Play.png') no-repeat center;
      background-size: 40%;
    }
    .vcp-playing .vcp-playtoggle {
      background: url('~assets/class/Pause.png') no-repeat center;
      background-size: 33%;
    }
    .vcp-fullscreen-toggle {
      background: url('~assets/class/Enlarge.png') no-repeat center;
      background-size: 45%;
    }
    // .vtp-player, .vcp-player, video {
    //   width: 100% !important;
    //   height: 100% !important;
    //   object-position: 0 0;
    // }
    // video {
    //   object-position: 0px 0px;
    // }
  }
}
</style>
